<?php
include_once ('dbconfig.php');
include_once ('config.php');
$con=mysql_connect('101.226.254.61','root','123456');
mysql_select_db('bs_cms');
mysql_set_charset('utf8');
if ($con=='') {
    echo '数据库连接失败';exit;
}

//验证数据库token是否过期
$sql_token="select * from `bs_token` ";
$query_token=mysql_fetch_assoc(mysql_query($sql_token));
$access_token=$query_token['token'];
$ctime=$query_token['ctime'];
$time=time();

if ($query_token=="" && $access_token=="") {
    $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APPID . "&secret=" . APPSECRET;
    $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
    //echo $res;
    $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
    $access_token = $result['access_token'];
    //print_r($access_token);exit;

    $sql="INSERT INTO bs_token (`token`,`ctime`) VALUE ('".$access_token."','".$time."')";
    $query=mysql_query($sql);
    if(empty($query)){
            exit('参数错误');
    }
    $query_token=mysql_fetch_assoc(mysql_query($sql_token));
    $access_token=$query_token['token'];
    $ctime=$query_token['ctime'];
}

$newtime=$ctime+7000;//提前刷新200秒   实际是7200秒
if ($newtime<$time) {
    $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APPID . "&secret=" . APPSECRET;
    $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
    //echo $res;
    $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
    $access_token = $result['access_token'];
    //print_r($access_token);exit;


    $sql="UPDATE bs_token SET token = '".$access_token."',ctime='".$time."'";
    $query=mysql_query($sql);
    if(empty($query)){
            exit('修改参数错误');
    }
    $query_token=mysql_fetch_assoc(mysql_query($sql_token));
    $access_token=$query_token['token'];
    $ctime=$query_token['ctime'];


}
?>